package org.jeecg.modules.solitaire_app.app.controller;

import java.util.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.solitaire_app.app.entity.YsyOnsiteApply;
import org.jeecg.modules.solitaire_app.app.entity.YsySealCarOrder;
import org.jeecg.modules.solitaire_app.app.entity.YsyUsers;
import org.jeecg.modules.solitaire_app.app.mapper.YsyOnsiteApplyMapper;
import org.jeecg.modules.solitaire_app.app.mapper.YsySealCarOrderMapper;
import org.jeecg.modules.solitaire_app.app.service.IYsyUsersService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * @Description: 小程序用户表
 * @Author: jeecg-boot
 * @Date: 2023-08-29
 * @Version: V1.0
 */
@Slf4j
@Api(tags = "小程序用户表")
@RestController
@RequestMapping("/app/ysyUsers")
public class YsyUsersController extends JeecgController<YsyUsers, IYsyUsersService> {
    @Autowired
    private IYsyUsersService ysyUsersService;
    @Autowired
    private YsySealCarOrderMapper ysySealCarOrderMapper;
    @Autowired
    private YsyOnsiteApplyMapper ysyOnsiteApplyMapper;

    /**
     * 分页列表查询
     *
     * @param ysyUsers
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "小程序用户表-分页列表查询")
    @ApiOperation(value = "小程序用户表-分页列表查询", notes = "小程序用户表-分页列表查询")
    @GetMapping(value = "/userList")
    public Result<?> userList(YsyUsers ysyUsers,
                              @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                              @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                              HttpServletRequest req) {
        QueryWrapper<YsyUsers> queryWrapper = QueryGenerator.initQueryWrapper(ysyUsers, req.getParameterMap());
        queryWrapper.eq("source", 1);
        Page<YsyUsers> page = new Page<YsyUsers>(pageNo, pageSize);
        IPage<YsyUsers> pageList = ysyUsersService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    /**
     * 分页列表查询
     *
     * @param ysyUsers
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "小程序用户表-分页列表查询")
    @ApiOperation(value = "小程序用户表-分页列表查询", notes = "小程序用户表-分页列表查询")
    @GetMapping(value = "/zcdList")
    public Result<?> zcdList(YsyUsers ysyUsers,
                             @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                             @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                             HttpServletRequest req) {
        QueryWrapper<YsyUsers> queryWrapper = QueryGenerator.initQueryWrapper(ysyUsers, req.getParameterMap());
        queryWrapper.eq("source", 2);
        Page<YsyUsers> page = new Page<YsyUsers>(pageNo, pageSize);
        IPage<YsyUsers> pageList = ysyUsersService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    /**
     * 分页列表查询
     *
     * @param orderId
     * @return
     */
    @AutoLog(value = "小程序用户表-查询可转单人员")
    @ApiOperation(value = "小程序用户表-查询可转单人员", notes = "小程序用户表-查询可转单人员")
    @GetMapping(value = "/getUserList/{orderId}")
    public Result<?> queryPageList(@PathVariable("orderId") String orderId) {
        YsySealCarOrder ysySealCarOrder = ysySealCarOrderMapper.selectOne(Wrappers.<YsySealCarOrder>lambdaQuery()
                .eq(YsySealCarOrder::getId, orderId));
        List<String> ids = new ArrayList<>();
        if (ObjectUtil.isNotNull(ysySealCarOrder.getIncomingUserId())) {
            ids.add(ysySealCarOrder.getIncomingUserId());
        }
        if (ObjectUtil.isNotNull(ysySealCarOrder.getTransferUserId())) {
            ids.add(ysySealCarOrder.getTransferUserId());
        }

        List<YsyUsers> ysyUsers = new ArrayList<>();
        if (ids.size() > 0) {
            ysyUsers = ysyUsersService.list(Wrappers.<YsyUsers>lambdaQuery()
                    .eq(YsyUsers::getSource, 2)
                    .eq(YsyUsers::getRealFlag, 1)
                    .notIn(YsyUsers::getId, ids));
        } else {
            ysyUsers = ysyUsersService.list(Wrappers.<YsyUsers>lambdaQuery()
                    .eq(YsyUsers::getSource, 2)
                    .eq(YsyUsers::getRealFlag, 1));
        }

        return Result.ok(ysyUsers);
    }

    @AutoLog(value = "小程序用户表-自动识别")
    @ApiOperation(value = "小程序用户表-自动识别", notes = "小程序用户表-自动识别")
    @GetMapping("/autoGetContent/{content}")
    public Result<JSONObject> autoGetContent(@PathVariable("content") String content) {
        Result<JSONObject> result = new Result<>();
        JSONObject jsonObject = new JSONObject();
        // 正则表达式模式匹配车牌号
        String licensePlatePattern = "[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼|]{1}[A-Z]{1}[A-Z_0-9]{5}";
        Pattern platePattern = Pattern.compile(licensePlatePattern);
        Matcher plateMatcher = platePattern.matcher(content);

        //车牌号
        while (plateMatcher.find()) {
            String licensePlate = plateMatcher.group();
            jsonObject.put("carNum", licensePlate);
        }

        // 正则表达式模式匹配手机号
        String phonePattern = "(1[3-9]\\d{9})";
        Pattern phoneNumPattern = Pattern.compile(phonePattern);
        Matcher phoneMatcher = phoneNumPattern.matcher(content);

        //手机号
        while (phoneMatcher.find()) {
            String phoneNumber = phoneMatcher.group();
            jsonObject.put("driverPhone", phoneNumber);
        }

        // 启发式方法匹配姓名
        String[] words = content.split("\\s+"); // 按空格分割文本
        for (String word : words) {
            if (word.length() >= 2 && Character.isUpperCase(word.charAt(0))) {
                // 假设姓名以大写字母开头，且长度大于等于2
                jsonObject.put("driverName", word);
            }
        }
        result.setSuccess(true);
        result.setCode(200);
        result.setResult(jsonObject);
        return result;
    }


    /**
     * 查询已入驻炼厂
     *
     * @param userId
     * @return
     */
    @AutoLog(value = "小程序用户表-查询已入驻炼厂")
    @ApiOperation(value = "小程序用户表-查询已入驻炼厂", notes = "小程序用户表-查询已入驻炼厂")
    @GetMapping(value = "/getUserRefinery/{userId}")
    public Result<?> getUserRefinery(@PathVariable("userId") String userId) {
        YsyOnsiteApply ysyOnsiteApply = ysyOnsiteApplyMapper.selectOne(Wrappers.<YsyOnsiteApply>lambdaQuery()
                .eq(YsyOnsiteApply::getUserId, userId));
        if (ObjectUtil.isNotEmpty(ysyOnsiteApply)) {
            return Result.ok(ysyOnsiteApplyMapper.getUserRefinery(Arrays.asList(ysyOnsiteApply.getRefineryIds().split(","))));
        }
        return Result.ok();
    }

    /**
     * 查询已入驻炼厂
     *
     * @param ysyUsers
     * @return
     */
    @AutoLog(value = "小程序用户表-查询已入驻炼厂")
    @ApiOperation(value = "小程序用户表-查询已入驻炼厂", notes = "小程序用户表-查询已入驻炼厂")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody YsyUsers ysyUsers) {
        ysyUsersService.save(ysyUsers);
        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     *
     * @param ysyUsers
     * @return
     */
    @AutoLog(value = "小程序用户表-编辑")
    @ApiOperation(value = "小程序用户表-编辑", notes = "小程序用户表-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody YsyUsers ysyUsers) {
        ysyUsersService.updateById(ysyUsers);
        return Result.ok("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "小程序用户表-通过id删除")
    @ApiOperation(value = "小程序用户表-通过id删除", notes = "小程序用户表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        ysyUsersService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "小程序用户表-批量删除")
    @ApiOperation(value = "小程序用户表-批量删除", notes = "小程序用户表-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.ysyUsersService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "小程序用户表-通过id查询")
    @ApiOperation(value = "小程序用户表-通过id查询", notes = "小程序用户表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        YsyUsers ysyUsers = ysyUsersService.getById(id);
        return Result.ok(ysyUsers);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param ysyUsers
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, YsyUsers ysyUsers) {
        return super.exportXls(request, ysyUsers, YsyUsers.class, "小程序用户表");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, YsyUsers.class);
    }

}
